let App = getApp();
Page({
  data: {
    carts: {},
    prompt: {
      hidden: !0,
      icon: '../../assets/images/iconfont-cart-empty.png',
      title: '购物车空空如也',
      text: '来挑几件好货吧',
      buttons: [{
        text: '随便逛',
        bindtap: 'toHome',
      }],
    },
    minusStatuses: [],
    selectedAllStatus: false,
    saveHidden: true,
    total: 0
  },
  onLoad () {
    let userId = wx.getStorageSync('userId')
    this.setData({ userId: userId })
  },
  onShow () {
    this.onPullDownRefresh()
    this.setData({ 
      selectedAllStatus: false,
      saveHidden: true,
      total: 0,
    })
  },
  toHome () {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },
  initData () {
    let userId = wx.getStorageSync('userId')
    this.setData({
      carts: {
        items: [],
        total: '',
        params: {
          buyerId: userId,
          page : 1,
          pageCount: 20
        }
      }
    })
  },
  getList (cb) { // 购物车列表
    let {carts, selectedAllStatus } = this.data
    let params = carts.params
    App.HttpService.cartList(params).then(res => {
      cb && cb()
      let data = res.data
      if (data.code == 200) {
        data.data.list.forEach(item => item.selected = selectedAllStatus)
        carts.items = [...carts.items, ...data.data.list]
        carts.total = data.data.counts
        this.setData({
          carts: carts,
          'prompt.hidden': carts.items.length,
        })
        this.sum()
      }
    }, e => {
      cb && cb()
    })
  },
  onPullDownRefresh () {
    wx.showNavigationBarLoading()
    this.initData()
    this.getList(() => {
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
    })
  },
  onReachBottom () {
    let carts = this.data.carts
    if (carts.items.length === carts.total) {
      return
    }
    this.getList()
  },
  editTap () {
    this.setData({
      saveHidden: !this.getSaveHide()
    })
  },
  saveTap () {
    this.setData({
      saveHidden: !this.getSaveHide()
    })
  },
  getSaveHide () {
    let saveHidden = this.data.saveHidden
    return saveHidden
  },
  bindMinus (e) { //减少
    let {index, id} = e.currentTarget.dataset
    index = parseInt(index)
    let carts = this.data.carts.items
    let num = carts[index].quantity
    if (num > 1) { // 如果只有1件了，就不允许再减了
      num--
      carts[index].quantity= num
      let minusStatuses = this.data.minusStatuses // 按钮可用状态
      minusStatuses[index] = minusStatus
      this.cartEdit({id: id, quantity: num}, () => {
        this.setData({
          'carts.items': carts,
          minusStatuses: minusStatuses
        })
        this.sum()
      })
    }
    let minusStatus = num <= 1 ? 'disabled' : 'normal' // 只有大于一件的时候，才能normal状态，否则disable状态
  },
  bindPlus (e) { // 增加
    let {index, id} = e.currentTarget.dataset
    index = parseInt(index)
    let carts = this.data.carts.items
    let num = carts[index].quantity 
    num++ // 自增
    let minusStatus = num <= 1 ? 'disabled' : 'normal' // 只有大于一件的时候，才能normal状态，否则disable状态
    carts[index].quantity = num
    let minusStatuses = this.data.minusStatuses // 按钮可用状态
    minusStatuses[index] = minusStatus
    this.cartEdit({id: id, quantity: num}, () => {
      this.setData({
        'carts.items': carts,
        minusStatuses: minusStatuses
      })
      this.sum()
    })
  },
  cartEdit (params, cb) { // 商品编辑
    App.HttpService.cartEdit(params).then(res => {
      let data = res.data
      if (data.code == 200) {
        cb && cb()
      }
    })
  },
  bindCheckbox (e) { /*绑定点击事件，将checkbox样式改变为选中与非选中*/
    let index = parseInt(e.currentTarget.dataset.index) //拿到下标值，以在carts作遍历指示用
    let carts = this.data.carts.items
    let selected = carts[index].selected //原始的icon状态
    carts[index].selected = !selected // 对勾选状态取反
    let selectedAllStatus = carts.every((item) => {
      return item.selected === true
    })
    this.setData({ 'carts.items': carts, selectedAllStatus })
    this.sum()
  },
  bindSelectAll () { // 点击全选
    let { selectedAllStatus } = this.data // 环境中目前已选状态
    selectedAllStatus = !selectedAllStatus
    let carts = this.data.carts.items
    carts.forEach(item => {
      item.selected= selectedAllStatus
    })
    this.setData({
      selectedAllStatus: selectedAllStatus,
      'carts.items': carts
    });
    this.sum()
  },
  toMerchants () { // 去选店
    let cartIds = this.calcIds()
    if (cartIds.length <= 0) {
      wx.showToast({
        title: '请勾选商品',
        image: '../../assets/images/warning.png',
        duration: 1000
      })
      return
    }
    let products = []
    let carts = this.data.carts.items
    carts.forEach(item => {
      if (item.selected) {
        let product = {
          id: item.productId,
          name: item.productName,
          image: item.image,
          price: item.price,
          num: item.quantity,
          unit: item.specification + item.unit
        }
        products.push(product)
      }
    })
    wx.setStorageSync('products', products)
    wx.navigateTo({
      url: '/pages/merchants/index?productStatus=0'
    })
  },
  deleteSelected (e) {
    let cartIds = this.calcIds()
    if (cartIds.length <= 0) {
      wx.showToast({
        title: '请勾选商品',
        image: '../../assets/images/warning.png',
        duration: 1000
      })
      return
    }
    cartIds = cartIds.join(',')
    wx.showModal({
      title: '提示',
      content: '确认要删除吗',
      success: (res) => {
        if (res.confirm) {
          this.cartDel(cartIds)
        }
      }
    })
  },
  cartDel (ids) { // 删除商品
    App.HttpService.cartDel({ids: ids}).then(res => {
      wx.showToast({
        title: '删除成功',
        icon: 'success',
        duration: 1500
      })
      this.onShow()
    })
  },
  calcIds () { // 遍历取出已勾选的cid
    let cartIds = []
    let carts = this.data.carts.items
    carts.forEach(item => {
      if (item.selected) {
        cartIds.push(item.id)
      }
    })
    return cartIds
  },
  sum () { // 计算总金额
    let carts = this.data.carts.items
    let total = 0
    carts.forEach(item => {
      if (item.selected) {
        total += item.quantity * item.price
      }
    })
    total = total.toFixed(2)
    this.setData({
      'carts.items': carts,
      total: total
    })
  },
  showGoods (e) {
    // 点击购物车某件商品跳转到商品详情
    let { productId } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/product/detail/detail?id=${productId}`
    });
  }
})